const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config');

Page({
  // 数据渲染
  data: {
    colorTheme: app.globalData.colorTheme,
    formats: {},
    readOnly: false,
    placeholder: '输入帖子内容...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    postInfo: null,
    forumList: [],
    forumId: -1
  },
  // 提交帖子
  submitPost(e){
    let params = e.detail.value;
    if(!params.title){
      wx.showToast({
        title: "标题不允许为空！",
        icon: 'none',
        duration: 1500,
      });
      return;
    }
    if(this.data.forumId === -1){
      wx.showToast({
        title: "请选择所属板块！",
        icon: 'none',
        duration: 1500,
      });
      return;
    }
    params.forumId = this.data.forumId;
    // 判断是更新帖子还是创建帖子
    if(this.data.postInfo !== null){
      params.id = this.data.postInfo.id;
    }
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'post/savePost';
    this.editorCtx.getContents({
      success(res){
        params.content = res.html.replace(/ wx:nodeid="\d+"/g,'');
        if(params.content === "<p><br></p>"){
          wx.showToast({
            title: "内容不允许为空！",
            icon: 'none',
            duration: 1500,
          });
          return;
        }
        wx.showLoading({
          title: '发布中...',
        });
        request.requestPostApi(url, token, params, 'application/json').then(res=>{
          if(res.status === config.STATUS_OK){
            wx.showToast({
              title: res.message,
              icon: 'success',
              duration: 1500,
            }); 
            wx.navigateBack({
              delta: 1
            });
          };
        }).catch(err => {
          app.failFun(err);
        }).finally((res) => {
          app.completeFun(res);
        });
      }
    });
  },
  // 获取更新帖子信息
  getPostInfo(id) {
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'index/post/detail/' + id;
    wx.showLoading({
      title: '加载ing'
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        this.setData({
          postInfo: res.data,
          forumId: res.data.forumId
        })
        that.onEditorReady()
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },
  // 获取模块列表
  getForumList(){
    let that = this;
    let url = config.SERVER_URL + 'forum/list/all';
    request.requestGetApi(url, {}, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          forumList: res.data
        });
      }
    }).catch(err=>{
      app.failFun(err);
    });
  },
  // 选择模块
  selectForum(e){
    this.setData({
      forumId: e.currentTarget.dataset.id
    })
  },
  // 只读
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  // 页面加载时触发的函数
  onLoad(e) {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
    this.getForumList()

    // 判断是否填充内容进行更新
    if(e.postId !== undefined){
      this.getPostInfo(e.postId);
    }
  },
  // 更新底部工具栏位置
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  // 识别运行环境
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  // editor加载完成执行的函数
  onEditorReady() {
    const that = this
    var postInfo = this.data.postInfo
    wx.createSelectorQuery().select('#editor').context(function (res) {
      if(postInfo){
        res.context.setContents({
          html: postInfo.content
        });
      }
      that.editorCtx = res.context
    }).exec()
  },
  // editor失去焦点执行函数
  blur() {
    this.editorCtx.blur()
  },
  // 定义格式
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  // 状态发生变化执行的函数
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  // 清空内容
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  // 移除格式
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  // 插入日期
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  // 插入图片
  insertImage() {
    const that = this
    let token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      success: function (res) {
        if(res.tempFiles.size > app.uploadFileMaxSize){
          wx.showToast({
            title: '上传文件不可超过11MB！',
            icon: 'none',
            duration: 1500
          });
          return;
        }
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '上传ing'
        });
        wx.uploadFile({
          url: config.SERVER_URL + 'user/uploadImage',
          filePath: tempFilePaths[0],
          name: 'image',
          header: {
            'UT-Token': token
          },
          success (res) {
            if (res.statusCode != config.STATUS_OK) {
              app.failFun(res, that);
            }
            let obj = JSON.parse(res.data);
            that.editorCtx.insertImage({
              src: obj.data.filePath,
              data: {
                id: 'abcd',
                role: 'god'
              },
              width: '80%',
              success: function () {
                console.log('insert image success')
              }
            })
            wx.hideLoading();
          }
        })
      }
    })
  }
})
